/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mongoosehome.web.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class EncodeUtils {
    private static final String DEFAULT_URL_ENCODING = "UTF-8";
    /**
     * 混淆码,防止破解,可以自己设置
     */
    private static String defaultSalt ="Mongoosehome";
    
    public static String encodePassword(String rawPass) {
        try {
            //默认加密字符串为密码+混淆码
            rawPass = rawPass+defaultSalt;
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(rawPass.getBytes());
            byte b[] = messageDigest.digest();
            int i;
            StringBuilder buf = new StringBuilder("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if(i<0) i+= 256;
                if(i<16)  buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            return buf.toString();
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(EncodeUtils.class.getName()).log(Level.SEVERE, null, ex);
            throw new IllegalArgumentException("No such algorithm [ MD5 ]");
        }
    }
    /**
     * 判断密码是否一样,一样返回true
     * @param encPass   MD5加密后的密码
     * @param rawPass   没有加密的密码
     * @return 
     */
    public static boolean isPasswordValid(String encPass, String rawPass) {
       if (encPass == null) {
            return false;
        }
        String pass2 = encodePassword(rawPass);
        return encPass.equals(pass2);
    }       

}
